﻿package com.pandemicode.framework.controls {
	import com.pandemicode.framework.localization.Locale;
	import com.pandemicode.framework.localization.LocaleManager;
	import flash.text.AntiAliasType;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	
	/**
	* @author Michael Lawrence
	* @version 1.0.0
	*/
	public class LocalizableTextField extends TextField {
		private var _stringID:String;
		
		/**
		 * A TextField that automatically updates when the LocaleManager changes locales.
		 * @param	stringID	The ID of the string to load.
		 */
		public function LocalizableTextField(stringID:String) {
			LocaleManager.instance.changed.add(this._onLocaleChanged);
			
			this._stringID = stringID;
			this.embedFonts = true;
			this.antiAliasType = AntiAliasType.ADVANCED;
			this.autoSize = TextFieldAutoSize.LEFT;
			this.selectable = false;
			this.type = TextFieldType.DYNAMIC;
			
			this.update();
		}
		
		/**
		 * Updates the text field's text and font.
		 */
		private function update():void {
			if(LocaleManager.instance.currentLocale != null) {
				var tf:TextFormat = this.getTextFormat();
				if (tf == null)
					tf = new TextFormat();
				tf.font = LocaleManager.instance.currentLocale.font.fontName;
				
				this.defaultTextFormat = tf;
				this.setTextFormat(tf);
				
				this.text = LocaleManager.instance.getString(this._stringID);
			}
		}
		
		/**
		 * Occurs when the locale changes.
		 * @param	e	The dispatched event.
		 */
		private function _onLocaleChanged(locale:Locale):void {
			this.update();
		}
	}
}
